package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.UserRoleMapper;
import com.cmii.sjw.department.control.jsc.model.entity.Menu;
import com.cmii.sjw.department.control.jsc.model.entity.Role;
import com.cmii.sjw.department.control.jsc.model.entity.UserRole;
import com.cmii.sjw.department.control.jsc.service.RoleMenuService;
import com.cmii.sjw.department.control.jsc.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jfh
 * @Date 2025-04-08 周二 11:09
 * @Version 1.0
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        List<UserRole> userRoles = this.lambdaQuery()
                .eq(UserRole::getUserId, userId)
                .list();
        if (CollectionUtils.isEmpty(userRoles)) {
            return Collections.emptyList();
        }
        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        return roleMenuService.getRolesByIds(roleIds);
    }

    @Override
    public List<Menu> getMenusByUserId(Long userId) {
        List<Role> roles = getRolesByUserId(userId);
        if (CollectionUtils.isEmpty(roles)) {
            return Collections.emptyList();
        }
        List<Long> roleIds = roles.stream()
                .map(Role::getId)
                .collect(Collectors.toList());
        return roleMenuService.getMenusByRoleIds(roleIds);
    }

    @Override
    public Long count(LambdaQueryWrapper<UserRole> eq) {
        if (eq != null) {
            return super.count(eq);
        }
        return 0L;
    }

    @Override
    public void remove(LambdaQueryWrapper<UserRole> eq) {
        if (eq != null) {
            super.remove(eq);
        }
    }

    @Override
    public boolean saveBatch(List<UserRole> userRoles) {
        if (!CollectionUtils.isEmpty(userRoles)) {
            return super.saveBatch(userRoles);
        }
        return false;
    }
}
